#! /usr/bin/python3

#coding=utf-8



import pty
import os
import select

'''
Linux虚拟串口
在终端下面输入：
sudo python virtualcom.py
便会显示：
slave device names:  /dev/pts/1 /dev/pts/2
这样/dev/pts/1与/dev/pts/2串口便相连接在一起了。
====================
$ ./virtualcom.py 
slave device names:  /dev/pts/3 /dev/pts/4
read 7 data.
read 14 data.
read 7 data.
read 14 data.
read 7 data.

'''

def mkpty():
    # 打开伪终端
    master1, slave = pty.openpty()
    slaveName1 = os.ttyname(slave)
    master2, slave = pty.openpty()
    slaveName2 = os.ttyname(slave)
    print( '\nslave device names: ', slaveName1, slaveName2 )
    return master1, master2


if __name__ == "__main__":

    master1, master2 = mkpty()
    while True:
        rl, wl, el = select.select([master1,master2], [], [], 1)
        for master in rl:
            data = os.read(master, 128)
            print("read %d data." % len(data))
            if master==master1:
                os.write(master2, data)
            else:
                os.write(master1, data)